<script setup>
import {
    getUserOneApi,
    getOrderUserPageApi,
    editUserApi
} from '@/api/user/personal.js'
import { ref, computed } from 'vue';
import {
    Tools,
    Right,
    CloseBold
} from '@element-plus/icons-vue'
import { statusOrderApi } from '@/api/backend/orders.js'
import { ElMessage, ElMessageBox } from 'element-plus'

const drawer = ref(false)
// 获取分页数据代码
const currentPage = ref(1)
const pageSize = ref(5)
const disabled = ref(false)
const total = ref(0)
const tableData = ref([])

const userOne = ref({
    avatar: '',
    id: '',
    idNumber: null,
    name: "",
    phone: "",
    sex: "1",
    status: 1
});
const getUserOne = async () => {
    let result = await getUserOneApi();
    if (result.code === 1) {
        userOne.value = result.data;
        return;
    } else {
        return;
    }
};
getUserOne();
const getImage = (image) => {
    return `/api/common/download?name=${image}`
}
const getOrderUserPage = async () => {
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
    }
    let result = await getOrderUserPageApi(params);
    if (result.code === 1) {
        tableData.value = result.data.records || [];
        total.value = result.data.total
        return;
    } else {
        return;
    }
};
getOrderUserPage();
const typeMapping = {
    1: '待付款',
    2: '待上餐',
    3: '已上餐',
    4: '已完成',
    5: '已取消'
}
const transformedTableData = computed(() => {
    return tableData.value.map(item => {
        return {
            ...item,
            status: typeMapping[item.status],
            amount: '￥' + item.amount / 100
        }
    })
})
const handleSizeChange = (val) => {
    // 调用获取分页数据方法
    getOrderUserPage();
}
const handleCurrentChange = (val) => {
    // 调用获取分页数据方法
    getOrderUserPage();
}
const openMessageBox = (i, s, x) => {
    ElMessageBox.confirm(
        '确定将订单状态更改?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 修改订单状态的代码
            switch (s) {
                case '待付款':
                    s = 1
                    break;
                case '待上餐':
                    s = 2
                    break;
                case '已上餐':
                    s = 3
                    break;
                case '已完成':
                    ElMessage.info('已完成订单无法修改')
                    return;
                case '已取消':
                    ElMessage.info('已取消订单无法修改')
                    return;
            }
            if (x != null) {
                switch (s) {
                    case 2:
                        ElMessage.info('待上餐订单无法取消')
                        return;
                    case 3:
                        ElMessage.info('已上餐订单无法取消')
                        return;
                    case 4:
                        ElMessage.info('已完成订单无法取消')
                        return;
                }
                s = 4;
                statusOrder(i, s);
            } else {
                statusOrder(i, s);
            }

        })
        .catch(() => {
            ElMessage.info('取消修改')
        })
}
const statusOrder = async (i, s) => {
    const params = {
        id: i,
        status: s + 1
    }
    let result = await statusOrderApi(params);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getOrderUserPage();
        return;
    } else {
        return;
    }
}
function cancelClick() {
    drawer.value = false
    ElMessage.info('退出用户信息修改')
}
function confirmClick() {
    ElMessageBox.confirm(`确认修改信息?`)
        .then(() => {
            submitForm(userRef)
                .then((result) => {
                    if (result) {
                        editUser();
                        drawer.value = false
                        return;
                    }
                    // 处理结果为 false 的情况
                });
        })
        .catch(() => {

            // catch error
        })
}
const onSuccess = (response, uploadFile) => {
    if (response.code === 1) {
        userOne.value.avatar = response.data;
    }
}
const beforeUpload = (uploadFile) => {
    if (uploadFile) {
        const suffix = uploadFile.name.split('.')[1];
        const size = uploadFile.size / 1024 / 1024 < 2;
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
            ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！');
            return false;
        }
        if (!size) {
            ElMessage.error('上传文件大小不能超过 2MB!');
            return false;
        }
        return true;
    }
}
const editUser = async () => {
    let result = await editUserApi(userOne.value);
    if (result.code === 1) {
        ElMessage.success(result.data);
        window.localStorage.setItem('username', userOne.value.name);
        location.reload();
        return;
    } else {
        return;
    }
};
const userRef = ref(null);
var phonereg = /^1[3456789]\d{9}$/;
var idNumberreg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
const userDataRules = {
    idNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: idNumberreg, message: '身份证号格式不正确', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: phonereg, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'blur' },
    ]
}
const submitForm = (fromEL) => {
    return new Promise((resolve, reject) => {
        fromEL.value.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        })
    });
}

</script>

<template>
    <el-card>
        <template #header>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-image style="width: auto; height: 60px; border:none;cursor: pointer;"
                        :src="getImage(userOne.avatar)" preview-teleported="true">
                        <template #error>
                            <img src="@\assets\default.png" style="width: auto; height: 60px; border:none;">
                        </template>
                    </el-image>
                </el-col>
                <el-col :span="12">
                    <el-tag type="success" size="large" style="width: 100%;">用户名:{{ userOne.name }}</el-tag>
                    <el-tag type="success" size="large" style="width: 100%;">手机:{{ userOne.phone }}</el-tag>
                </el-col>
                <el-col :span="6">
                    <el-button :icon="Tools" circle style="height: 100%;width: auto;font-size: 40px;"
                        @click="drawer = true" />
                </el-col>
            </el-row>
        </template>
        <el-table :data="transformedTableData" :border="parentBorder" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }">
            <el-table-column type="expand" width="30">
                <template #default="{ row }">
                    <div>
                        <el-table :data="row.orderDetails" stripe style="width: 100%" :cell-style="{ textAlign: 'center' }"
                            :header-cell-style="{ 'text-align': 'center' }">
                            <el-table-column label="名称" prop="name" width="180px"></el-table-column>
                            <el-table-column label="图片" prop="image" align="center">
                                <template #default="{ row }">
                                    <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                                        :src="`/api/common/download?name=${row.image}`">
                                        <template #error>
                                            <img src="@\assets\noImg.png" style="width: auto; height: 40px; border:none;">
                                        </template>
                                    </el-image>
                                </template>
                            </el-table-column>
                            <el-table-column label="口味" prop="dishFlavor">
                                <template #default="{ row }">
                                    {{ (row.dishFlavor == null ? '无' : row.dishFlavor) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" prop="number"></el-table-column>
                            <el-table-column label="金额" prop="amount">
                                <template #default="{ row }">
                                    {{ row.amount / 100 }}
                                </template>
                            </el-table-column>
                            <template #empty>
                                <el-empty description="没有数据" />
                            </template>
                        </el-table>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="90">
                <template #default="{ row }">
                    {{ row.status }}
                    <el-button :icon="Right" circle size="small" @click="
                        openMessageBox(row.id, row.status)" type="warning" />
                    <el-button :icon="CloseBold" circle size="small" @click="
                        openMessageBox(row.id, row.status, 'x')" type="danger" />
                </template>
            </el-table-column>
            <el-table-column label="订单号" prop="number" width="180" />
            <el-table-column label="金额" prop="amount" width="140" />
            <el-table-column label="时间" prop="orderTime" width="180" />
        </el-table>
        <div>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 15, 30]"
                :small="small" :disabled="disabled" :background="background" layout="sizes, prev, pager, next"
                :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <el-drawer v-model="drawer" title="用户信息编辑" :close-on-click-modal="false" :close-on-press-escape="false"
            :show-close="false" direction='rtl' size="100%">
            <el-form label-position="top" label-width="100px" :model="userOne" ref="userRef" :rules="userDataRules">
                <el-form-item label="头像">
                    <el-upload action="/api/common/upload" :show-file-list="false" :on-success="onSuccess"
                        :before-upload="beforeUpload" ref="upload">
                        <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                            :src="getImage(userOne.avatar)" preview-teleported="true">
                            <template #error>
                                <img src="@\assets\noImg.png" style="width: auto; height: 40px; border:none;">
                            </template>
                        </el-image>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户名"  prop="name">
                    <el-input v-model="userOne.name" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userOne.sex">
                        <el-radio label='1'>
                            男
                        </el-radio>
                        <el-radio label='0'>
                            女
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="userOne.phone" />
                </el-form-item>
                <el-form-item label="身份证号" prop="idNumber">
                    <el-input v-model="userOne.idNumber" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelClick">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确认</el-button>
                </div>
            </template>
        </el-drawer>
    </el-card>
</template>

<style lang="scss" scoped>
.el-pagination {
    margin-top: 10px;
    justify-content: center;
}
</style>